<!-- 用户管理 -->
<template>
  <div class="app-container">
    <avue-crud
      v-model:search="search"
      :page="page"
      :data="pageData?.data"
      :option="option"
      :table-loading="loading"
      @search-change="searchChange"
      @search-reset="handleQuery"
      @current-change="currentChange"
      @refresh-change="handleQuery"
      @row-del="handleDelete"
    >
      <template #menu-left="{ size }">
        <el-button type="primary" icon="el-icon-plus" :size="size" @click="handleAdd">
          新增
        </el-button>
      </template>

      <template #menu="{ size, row, index }">
        <el-button icon="el-icon-edit" text type="primary" :size="size" @click="handleEdit(row.id)">
          编辑
        </el-button>
      </template>
    </avue-crud>
  </div>
</template>

<script setup lang="ts">
import { PageDataModel } from "@/model/page-data-model";
import router from "@/router";
import adminListOptions, { AdminListSearchModel } from "./avue-options";
import { UserModel } from "@/model/user-model";
import AdminAPI from "@/api/system/admin";

defineOptions({
  name: "AdminList",
  inheritAttrs: false,
});

const search = ref<AdminListSearchModel>({});
const option = ref(adminListOptions);
const pageData = ref<PageDataModel<UserModel[]>>();
const loading = ref(false);

const page = computed(() => {
  return {
    ...pageData.value,
    layout: "total, prev, pager, next, jumper",
  };
});

/**
 * @description 查询数据
 */
async function handleQuery() {
  loading.value = true;
  AdminAPI.getPage(search.value)
    .then((res: any) => {
      pageData.value = res;
    })
    .finally(() => {
      loading.value = false;
    });
}

/**
 * @description 分页切换
 * @param val  当前页码
 */
function currentChange(val: number) {
  search.value.page = val;
  handleQuery();
}

/**
 * 处理搜索变化的函数
 * 当搜索条件变化时，此函数会被调用，通常用于处理搜索前的准备工作和搜索完成后的回调
 *
 * @param {Object} params - 包含搜索条件的参数对象
 * @param {Function} done - 一个回调函数，用于通知搜索操作完成
 */
function searchChange(params: Object, done: Function) {
  handleQuery().then(() => {
    done();
  });
}

/**
 * @description 查看用户按钮点击事件
 * @param id 用户ID
 */
function onDetailClick(id: number) {
  router.push({
    path: "/user/detail",
    query: { id },
  });
}

/**
 * @description 新增管理员
 */
function handleAdd() {
  router.push({
    path: "/system/admin/add",
  });
}
/**
 * @description 编辑管理员
 */
function handleEdit(id: number) {
  router.push({
    path: "/system/admin/edit",
    query: { id },
  });
}

/**
 * @description 行删除事件
 * @param row 行数据
 * @param index 行索引
 */
async function handleDelete(row: any, index: number) {
  try {
    await ElMessageBox.confirm("确认删除这条数据吗?", "警告");
    await AdminAPI.delete(row.id);

    // 删除行数据
    if (pageData.value && Array.isArray(pageData.value.data)) {
      pageData.value.data.splice(index, 1);
    }
    ElMessage.success("删除成功");
  } catch (error) {
    console.error(error);
  }
}

onMounted(() => {
  handleQuery();
});
</script>
